<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\LihuaOrder;
use app\common\model\general\LihuaCity;
use app\common\model\LihuaOrderPayment;
use app\common\model\LihuaPaylog;
use app\common\model\LihuaRefund;
use app\common\model\User;
use app\common\model\LihuaWalletOrder;
use app\common\model\OrderRandomFee;
use app\common\model\LihuaOrderActivity;
use app\common\model\LihuaVouchers; //现金抵用券
use app\common\model\LihuaVouchersLog; //现金抵用券使用记录
use my\WxPay;
use my\AliPay;
use think\Db;
use fast\Http;
use think\Exception;
use think\Log;

/**
 * 支付
 */
class Pay extends Api
{
    protected $_error = '';
    protected $noNeedLogin = [
		//下单支付
		'wxpay', //微信支付
		'wxcb', //微信支付回调
		'alipay', //支付宝支付
		'alicb', //支付宝支付回调
		'code',  //货到付款
		'vip', //VIP卡支付
		'walletpay', //使用余额支付订单
		'walletpay2', //使用钱包剩余金额抵扣部分订单金额
		'xcx_wxpay', //小程序下单支付

		// 钱包充值支付
		// 'wallet_wxpay', //钱包账号在线充值，微信支付
		'wallet_wxcb', //钱包账号在线充值，微信支付回调
		'wallet_wx_yl_cb', //钱包账号在线充值，银联微信支付回调
		'wallet_alipay', //钱包账号在线充值，支付宝支付
		'wallet_alicb', //钱包账号在线充值，支付宝支付回调
		
		//钱包支付相关活动接口
		'random_fee', //生成随机减免金额
		'getWalletAct', //获取某城市的钱包支付优惠活动

		'unionpay_yunpay', //app银联云闪付
		'unionpay_yuncb', //app银联云闪付回调
		'unionpay_act', //云闪付活动

		'unionpay_wxpay', //银联微信支付
		'unionpay_wxcb', //银联微信支付回调

		'unionpay_alipay', //银联支付宝支付
		'unionpay_alicb', //银联支付宝支付回调
		'unionpay_wx_queryRefund', //银联微信退款接口
		'unionpay_wx_refundcb', //银联微信退款回调接口

		'test_updata_walletOrder', //更新钱包充值订单表的充值订单ID

        'micro_voucher', //线下现金抵扣券扫码消费
		'micro_voucher_bc', //现金抵扣券恢复
		
	];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();
	}

	/**
	 * 支付失败后现金抵扣券恢复
	 * **/
	public function micro_voucher_bc(){
		$voucher_sn = $this->request->request('voucher_sn', '');//卡券编号

		//回复现金券状态
		$res = LihuaVouchers::update([
			'status' => 0,
			'order_sn' => '',
			'use_time' => '',
			'update_time'=> time(),
		], ['sn' => $voucher_sn]);

		//删除现金券使用日志
		LihuaVouchersLog::where(['voucher_sn' => $voucher_sn])->delete();

		$this->success('ok', $s);
	}

	/**
	 * 线下现金抵扣券扫码消费
	 * **/
    public function micro_voucher(){
        $sn = $this->request->request('sn', ''); //订单编号,此订单编号，在用户扫码的时候生成
		$cityname = $this->request->request('cityname', '');//城市名称
		$voucher_sn = $this->request->request('voucher_sn', '');//卡券编号
		// $uid = $this->request->request('uid');//用户id
		$price = $this->request->request('price', 0);//订单金额
		
		
		//首先获取抵扣券的相关信息
		$voucher_info = LihuaVouchers::where([
			'sn' => $voucher_sn
		])->find();

		//获取城市信息
		$citys = LihuaCity::where(['id'=> $voucher_info['city_id']])->find();
		//获取用户信息
		$users = User::where([ 'id' => $voucher_info['user_id'] ])->find();

		$day = date('Y-m-d');
		if(!!$voucher_info){
			if($voucher_info['status']!=0){
				$this->error('抵扣券已失效');
			}
			if($voucher_info['end_date']<$day){
				$this->error('抵扣券已过期失效');
			}
			if($citys['name']!=$cityname){
				$this->error('请在仅能在'.$citys['name'].'地区使用');
			}
		}else{
			$this->error('该券码无效');
		}
		//开启数据库事务
		Db::startTrans();
        try {
			//到此说明抵扣券可以用于消费抵扣，进行消费使用
			$res = LihuaVouchers::update([
				'status' => 1,
				'order_sn' => $sn,
				'use_time' => date('Y-m-d H:i:s'),
				"update_time"	=> time(),
			], ['sn' => $voucher_sn]);
			//生成使用记录
			$datas = [
				"city_id"		=> $voucher_info['city_id'],
				"user_id"		=> $voucher_info['user_id'],
				"day"			=> date('Y-m-d'),
				"voucher_sn"	=> $voucher_sn,
				"order_sn"		=> $sn,
				"use_type"		=> 3,//线下扫码抵扣
				"use_time"		=> date('Y-m-d H:i:s'),
				"create_time"	=> time(),
				"update_time"	=> time(),
			];
			$ret = LihuaVouchersLog::create($datas);
			Db::commit();
		}catch (Exception $e) {
            Db::rollback();
            $this->error('提交失败，请尝试重新提交');
        }

		//计算扣除后的剩余金额
		$r_price = bcsub($price, $voucher_info['price'], 2);
		if($r_price<0) $r_price = 0;
		
		$data = [
			'price' => $r_price,//剩余支付金额
			'sn' => $sn,//订单编号，私定系统生成的订单编号
			'mobile' => $users['mobile'], //用户手机号
			'voucher_proce' => $voucher_info['price'],//现金抵扣券抵扣的金额
		];
		$this->success('ok', $data);
    }

	/***
	 * 云闪付活动名称
	*/
	public function unionpay_act(){
		$city_id = (int)$this->request->request('city_id', 0);
		//城市id对应的活动名称
		$act_arr = [
			1 => ["随机立减1-199元"],
			2 => ["随机立减1-199元"],
			3 => ["随机立减1-199元"],
			4 => ["随机立减1-199元"],
			5 => ["随机立减1-199元"],
			6 => ["随机立减1-199元"],
			7 => ["随机立减1-199元"]
		];
		$this->success( '返回成功', $act_arr[$city_id] );
	}

	/*更新钱包充值订单表的充值订单ID*/
	public function test_updata_walletOrder(){
		//查询出没有wallet_id的记录
		$list = LihuaWalletOrder::where(['wallet_id'=> 0])->select();
		foreach ($list as $key => $value) {
			# code...
			if($value['wallet_id']==0){
				$value['wallet_id'] = $value['id'];
				$value->save();
			}
		}
		$this->success('返回成功', $list);
	}

	/*银联app云闪付*/
	public function unionpay_yunpay(){
		$sn  = $this->request->request('sn');
        $arr = $this->getOrderInfoAndPayConf($sn, 2);
        if ($arr === false) $this->error($this->getError());
		list($info, $conf) = $arr;
		$config = [
			'mch_id'     	=> $conf['mch_id'],//商户号
			'api_key'    	=> $conf['api_key'],//微信商户平台上自己设定的api密钥32位
			'notify_url' 	=> config('api_url') . '/pay/unionpay_yuncb.html',//回调地址
			'trade_type'	=> 'JSAPI',
			'mid'			=> $conf['app_mid'],
			'tid'			=> $conf['app_tid'],
		];
		$wxpay 	= new WxPay($config);
		$url   	= "https://qr.chinaums.com/netpay-route-server/api/";
		// $url  	= "https://qr-test2.chinaums.com/netpay-route-server/api/";

		$n_pay_money = bcsub($info['order_amount'], $info['wallet_money_pay'], 2); //wallet_money_pay,wallet_given_fee

		$data  	= $wxpay->unionpay_yun_unifiedOrder($sn, $n_pay_money);
		$params = json_encode($data);
		$ret 	= Http::post($url, $params);
		$res 	= json_decode($ret, true);
		$this->success('返回成功', $res);
	}
	
	/*银联app云闪付回调*/
	public function unionpay_yuncb(){
		$xml   = file_get_contents('php://input');
		$wxpay = new WxPay();
		Log::record('[ wxcb_yinlian_klk_htmlspecialchars::->order_money   ] INIT ' . htmlspecialchars($xml) , 'info');
        	$res   = $wxpay->xmlstr_to_array_unionpay($xml);
        if ($res['status'] == 'TRADE_SUCCESS') {
			$merOrderId = explode("LHKC", $res['merOrderId']);
			// $row = $this->getOrderInfo($merOrderId[1]);
			$row = LihuaOrder::where(['sn'=> $merOrderId[1]])->find();
			if ($row) {
				// $money = $res['totalAmount'];
				$money = round($res['totalAmount']/100, 2);
				$order_amount = $row['order_amount'];
				// $checkMoney = (($order_amount * 100) == $res['totalAmount']);
				// Log::record('[ wxcb_yinlian::->order_money res_total_fee  ] INIT ' . ($order_amount * 100) . ':::' .$res['totalAmount'] . ':::::' . $checkMoney , 'info');
				$pay_time = date('Y-m-d H:i:s');
				if ($res['status'] == 'TRADE_SUCCESS') {
					$pay_ok = 1;
					$result_des = '交易支付成功';
				} else {
					$pay_ok = 0;
					$dis = [
						"NEW_ORDER" => "新订单",
						"UNKNOWN" => "不明确的交易状态",
						"TRADE_CLOSED" => "支付失败",
						"WAIT_BUYER_PAY" => "等待买家付款",
						"TRADE_SUCCESS" => "支付成功",
						"TRADE_REFUND" => "订单转入退货流程",
					];
					$result_des = $res['status'].'：'.$dis[$res['status']];
				}

				if (!isset($pay_time)) $pay_time = date('Y-m-d H:i:s');
				$data = [
					'type'           => 7,//云闪付
					'trade_no'       => $merOrderId,
					'out_trade_no'   => $merOrderId[1],
					'total_fee'      => $money,
					'order_id'       => $row['id'],
					'user_id'        => $row['user_id'],//$res['attach']
					'pay_ok'         => $pay_ok,
					'pay_time'       => $pay_time,
					'result_code'    => $res['status'],
					'result_des'     => $result_des,
					'callbackdata'   => json_encode($res, JSON_UNESCAPED_UNICODE),
				];

				$paylog = LihuaPaylog::create($data);

				if ($res['status'] == 'TRADE_SUCCESS' && $row['status'] == 1) {
					$data = [
						'pay_type'   => 7, //云闪付
						'pay_status' => 1,
						'pay_time'   => $pay_time,
						'status'     => 2,
						'merorder_id'=> $res['merOrderId'],
					];
					LihuaOrder::update($data, ['id' => $row['id']]);//跟新订单状态
					$this->updateOrderAct($row['sn']);
					LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
					LihuaOrderPayment::create([
						'city_id'    => $row['city_id'],
						'order_id'   => $row['id'],
						'order_sn'   => $row['sn'],
						'user_id'    => $row['user_id'],
						'pay_name'   => '云闪付',
						'pay_money'  => $money,
						'is_voucher' => 0,
					]);
				}
			}
        }
        return xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
	}
	
	/*银联微信支付  已经切换到 n_pay_money*/ 
	public function unionpay_wxpay(){
		$sn  = $this->request->request('sn');
        $arr = $this->getOrderInfoAndPayConf($sn, 2);
        if ($arr === false) $this->error($this->getError());
		list($info, $conf) = $arr;
		$config = [
			'appid'      => $conf['xcx_id'],//微信开放平台上的应用ID
			'mch_id'     => $conf['mch_id'],//商户号
			'api_key'    => $conf['api_key'],//微信商户平台上自己设定的api密钥32位
			'notify_url' => config('api_url') . '/pay/unionpay_wxcb.html',//回调地址 
			'trade_type' => 'JSAPI',
		];
		$js_code = $this->request->request('js_code');
		$url = 'https://api.weixin.qq.com/sns/jscode2session';
		$params = [
			'appid'   		=> $conf['xcx_id'],
			'secret'  		=> $conf['app_secret'], //应用secret
			'js_code' 		=> $js_code,
			'grant_type' 	=> 'authorization_code',
		];
		$ret = Http::post($url, $params);
		$result = json_decode($ret, true);
		$config['mid'] = $conf['mid'];
		$config['tid'] = $conf['tid'];
		$config['openid'] = isset($result['openid'])?$result['openid']:"";
		$wxpay 	= new WxPay($config);
		$url   	= "https://qr.chinaums.com/netpay-route-server/api/";
		$n_pay_money = bcsub($info['order_amount'], $info['wallet_money_pay'], 2); //wallet_money_pay,wallet_given_fee
		$data  	= $wxpay->unionpay_unifiedOrder($sn, $n_pay_money);
		$params = json_encode($data);
		$ret 	= Http::post($url, $params);
		$res 	= json_decode($ret, true);
		$this->success('返回成功', $res);
	}

	/*银联微信支付回调*/
	public function unionpay_wxcb(){
		$xml   = file_get_contents('php://input');
		$wxpay = new WxPay();
		
        $res   = $wxpay->xmlstr_to_array_unionpay($xml);
        if ($res['status'] == 'TRADE_SUCCESS') {
			$merOrderId = explode("_", $res['merOrderId']);
			// Log::record('[ unionpay_wxcb ] INIT ' . $merOrderId[1] . "_" . $res['merOrderId'], 'info');
			$row = LihuaOrder::where(['sn'=> $merOrderId[1]])->find();
			if ($row) {
				$money = round($res['totalAmount']/100, 2);
				$order_amount = $row['order_amount'];
				// $checkMoney = (($order_amount * 100) == $res['totalAmount']);
				// Log::record('[ wxcb_yinlian::->order_money res_total_fee  ] INIT ' . ($order_amount * 100) . ':::' .$res['totalAmount'] . ':::::' . $checkMoney , 'info');
				$pay_time = date('Y-m-d H:i:s');
				if ($res['status'] == 'TRADE_SUCCESS') {
					$pay_ok = 1;
					$result_des = '交易支付成功';
				} else {
					$pay_ok = 0;
					$dis = [
						"NEW_ORDER" => "新订单",
						"UNKNOWN" => "不明确的交易状态",
						"TRADE_CLOSED" => "支付失败",
						"WAIT_BUYER_PAY" => "等待买家付款",
						"TRADE_SUCCESS" => "支付成功",
						"TRADE_REFUND" => "订单转入退货流程",
					];
					$result_des = $res['status'].'：'.$dis[$res['status']];
				}

				if (!isset($pay_time)) $pay_time = date('Y-m-d H:i:s');
				$data = [
					'type'           => 6,//微信支付
					'trade_no'       => $merOrderId,
					'out_trade_no'   => $merOrderId[1],
					'total_fee'      => $money,
					'order_id'       => $row['id'],
					'user_id'        => $row['user_id'],//$res['attach']
					'pay_ok'         => $pay_ok,
					'pay_time'       => $pay_time,
					'result_code'    => $res['status'],
					'result_des'     => $result_des,
					'callbackdata'   => json_encode($res, JSON_UNESCAPED_UNICODE),
				];

				$paylog = LihuaPaylog::create($data);

				if ($res['status'] == 'TRADE_SUCCESS' && $row['status'] == 1) {
					$data = [
						'pay_type'   => 6,
						'pay_status' => 1,
						'pay_time'   => $pay_time,
						'status'     => 2,
						'merorder_id'=> $res['merOrderId'],
					];
					LihuaOrder::update($data, ['id' => $row['id']]);//跟新订单状态
					$this->updateOrderAct($row['sn']);
					LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
					LihuaOrderPayment::create([
						'city_id'    => $row['city_id'],
						'order_id'   => $row['id'],
						'order_sn'   => $row['sn'],
						'user_id'    => $row['user_id'],
						'pay_name'   => '微支付YL',
						'pay_money'  => $money,
						'is_voucher' => 0,
					]);
				}
			}
        }
        return xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
	}

	/*银联微信-退款接口*/
	public function unionpay_wx_queryRefund()
	{
		$sn  = $this->request->request('sn');
        $arr = $this->getOrderInfoAndPayConf_refund($sn, 2);
        if ($arr === false) $this->error($this->getError());
		list($info, $conf) = $arr;
		$notify_url = $this->request->domain() . '/api/pay/unionpay_wx_refundcb.html';
		$config = [
			'appid'      	=> $conf['xcx_id'],//微信开放平台上的应用ID
			'mch_id'     	=> $conf['mch_id'],//商户号
			'api_key'    	=> $conf['api_key'],//微信商户平台上自己设定的api密钥32位
			'notify_url' 	=> $notify_url,//回调地址 
			'trade_type' 	=> 'JSAPI',
		];
		$config['mid'] = $conf['mid'];
		$config['tid'] = $conf['tid'];
		$wxpay = new WxPay($config);
		$cityname = '';
		if($info['city_name']=='常州'){ $cityname = 'cz'; };
		if($info['city_name']=='无锡'){ $cityname = 'wx'; };
		if($info['city_name']=='苏州'){ $cityname = 'sz'; };
		if($info['city_name']=='上海'){ $cityname = 'sh'; };
		if($info['city_name']=='南京'){ $cityname = 'nj'; };
		if($info['city_name']=='北京'){ $cityname = 'bj'; };
		if($info['city_name']=='广州'){ $cityname = 'gz'; };
		$body   = "lihua-{$cityname}-{$sn}";
		$data   = $wxpay->xcx_unifiedOrder_refund($sn, $info['order_amount'], $body, $cityname, $info['order_amount'], $info['merorder_id']);
		$params = json_encode($data);
		$url   	= "https://qr.chinaums.com/netpay-route-server/api/";
		$ret 	= Http::post($url, $params);
		$res 	= json_decode($ret, true);
		if($res['errCode'] == 'SUCCESS'){
			$merOrderId = explode("_", $res['merOrderId']);
			$updata_order = LihuaOrder::where([ 'sn'=>$sn ])->update([ 'status'=>0 ]);
			$updata_refund = LihuaRefund::where([ 'order_sn'=>$sn ])->update([ 'status'=>1 ]);
			$this->success('OK', ['data'=>$res, 'updata_order'=>$updata_order, 'updata_refund'=>$updata_refund ]);
		}else{
			$this->error($res);
		}
	}

	/*银联支付回调接口*/
	public function unionpay_wx_refundcb()
	{
        $xml   = file_get_contents('php://input');
        $wxpay = new WxPay();
        $res   = $wxpay->xmlstr_to_array($xml);
        if ($res['return_code'] == 'SUCCESS') {
            if ($res['result_code'] == 'SUCCESS') {
                $row = $this->getOrderInfo($res['out_trade_no']);
                if ($row) {
                    $money = $row['order_amount'];
                    // $checkMoney = (($money * 100) == $res['total_fee']);
					// Log::record('[ wxcb::->order_money res_total_fee  ] INIT ' . ($money * 100) . ':::' .$res['total_fee'] . ':::::' . $checkMoney , 'info');
					if ($res['time_end']) {
						$time_end = date_create($res['time_end']);
						$pay_time = date_format($time_end,"Y-m-d H:i:s");
					}

					if ($res['result_code'] == 'SUCCESS') {
						$pay_ok = 1;
						$result_des = '交易支付成功';
					} else {
						$pay_ok = 0;
						$result_des = $res['err_code'].'：'.$res['err_code_des'];
					}

					if (!isset($pay_time)) $pay_time = date('Y-m-d H:i:s');
					$data = [
						'type'           => 2,//微信支付
						'trade_no'       => $res['transaction_id'],
						'out_trade_no'   => $res['out_trade_no'],
						'total_fee'      => $money,
						'order_id'       => $row['id'],
						'user_id'        => $row['user_id'],//$res['attach']
						'pay_ok'         => $pay_ok,
						'pay_time'       => $pay_time,
						'result_code'    => $res['result_code'],
						'result_des'     => $result_des,
						'callbackdata'   => json_encode($res, JSON_UNESCAPED_UNICODE),
					];

					$paylog = LihuaPaylog::create($data);

					if ($res['result_code'] == 'SUCCESS' && $row['status'] == 1) {
						$data = [
							'pay_type'   => 6,
							'pay_status' => 1,
							'pay_time'   => $pay_time,
							'status'     => 2,
						];
						LihuaOrder::update($data, ['id' => $row['id']]);//跟新订单状态

						$this->updateOrderAct($row['sn']);

						LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
						LihuaOrderPayment::create([
							'city_id'    => $row['city_id'],
							'order_id'   => $row['id'],
							'order_sn'   => $row['sn'],
							'user_id'    => $row['user_id'],
							'pay_name'   => '微支付',
							'pay_money'  => $money,
							'is_voucher' => 0,
						]);
					}
                }
            }
        }
        return xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
    }

    /**设置错误信息
     * .
     * @ApiInternal()
     */
    public function setError($error)
    {
        $this->_error = $error;
	}
	
	/**生成随机减免金额
     * .
	 * 
	 * 根据订单金额生成随机减免金额 （大金额优惠1/1000的概率会出现，小金额优惠999/1000的概率会出现）
	 * 金额 1-50       大概率优惠 1-3       小概率优惠 6-7     (1概率23/30 2概率6/30 3概率1/30)
	 * 金额 51-100     大概率优惠 1-6       小概率优惠 10-13   (1概率22/60 2概率16/60 3概率10/60 4概率6/60 5概率4/60 6概率2/60)
	 * 金额 101-200    大概率优惠 1-10      小概率优惠 16-19   (1概率30/100 2概率24/100 3概率18/100 4概率12/100 5概率6/100 6概率4/100 7概率2/100 8概率2/100 9概率1/100 10概率1/100)
	 * 金额 201 以上    大概率优惠 1-12      小概率优惠 21-22   (1概率32/130 2概率28/130 3概率18/130 4概率14/130 5概率12/130 6概率8/130 7概率6/130 8概率4/130 9概率4/130 10概率2/130 11概率1/130 12概率1/130 )
	 * 小概率优惠最大9折 大概率优惠最大8折
     */
	public function random_fee(){
		$sn = $this->request->request('sn'); //2003216350560430
		$order = LihuaOrder::where(array('sn'=>$sn))->find();
		$price = $order['order_amount'];
		if($order['pay_status']==0 && $order['status']==1){
			//判断该订单是否进行过随机立减的计算
			$has_fee = OrderRandomFee::where(['order_sn' => $sn])->find();
			if($has_fee){
				$this->success('ok', $has_fee['fee']);
			}else{

				$mini_fee_arr = array();
				$max_fee_arr = array();
				//(1概率23/30 2概率6/30 3概率1/30)
				if($price<=50 && $price>1){ 
					$mini_fee_arr = array(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,3); 
					$max_fee_arr = array(5,5,5,5,5,5,6);
				}
				//(1概率28/60 2概率17/60 3概率6/60 4概率4/60 5概率3/60 6概率2/60)
				if($price<=100 && $price>50){ 
					$mini_fee_arr = array(
										1,1,1,1,1,1,1,1,1,1,
										1,1,1,1,1,1,1,1,1,1,
										1,1,1,1,1,1,1,1,
										2,2,2,2,2,2,2,2,2,2,
										2,2,2,2,2,2,2,
										3,3,3,3,3,3,
										4,4,4,4,
										5,5,5,
										6,6
										); 
					$max_fee_arr = array(10,10,10,10,10,10,11,11,11,11,11,12,13);
				}
				//(1概率35/100 2概率25/100 3概率15/100 4概率9/100 5概率6/100 6概率4/100 7概率2/100 8概率2/100 9概率1/100 10概率1/100)
				if($price<=200 && $price>100){ 
					$mini_fee_arr = array(
										1,1,1,1,1,1,1,1,1,1,
										1,1,1,1,1,1,1,1,1,1,
										1,1,1,1,1,1,1,1,1,1,
										1,1,1,1,1,
										2,2,2,2,2,2,2,2,2,2,
										2,2,2,2,2,2,2,2,2,2,
										2,2,2,2,2,
										3,3,3,3,3,3,3,3,3,3,
										3,3,3,3,3,
										4,4,4,4,4,4,4,4,4,
										5,5,5,5,5,5,
										6,6,6,6,
										7,7,
										8,8,
										9,
										10
										);
					$max_fee_arr = array(16,16,16,16,16,16,17,17,17,17,17,18,19);
				}
				//(1概率36/130 2概率30/130 3概率20/130 4概率14/130 5概率10/130 6概率7/130 7概率5/130 8概率3/130 9概率2/130 10概率1/130 11概率1/130 12概率1/130 )
				if($price>200){ 
					$mini_fee_arr = array(
						1,1,1,1,1,1,1,1,1,1,
						1,1,1,1,1,1,1,1,1,1,
						1,1,1,1,1,1,1,1,1,1,
						1,1,1,1,1,1,
						2,2,2,2,2,2,2,2,2,2,
						2,2,2,2,2,2,2,2,2,2,
						2,2,2,2,2,2,2,2,2,2,
						3,3,3,3,3,3,3,3,3,3,
						3,3,3,3,3,3,3,3,3,3,
						4,4,4,4,4,4,4,4,4,4,
						4,4,4,4,
						5,5,5,5,5,5,5,5,5,5,
						6,6,6,6,6,6,6,
						7,7,7,7,7,
						8,8,8,
						9,9,
						10,
						11,
						12
					); 
					$max_fee_arr = array(22,22,22,22,23);
				}
				//随机出判断是小额优惠还是大额优惠
				$fee_type = rand(1, 1000);
				$fee_arr = array();
				if($fee_type==999){
					$fee_arr = $max_fee_arr;
				}else{
					$fee_arr = $mini_fee_arr;
				}
				//计算出随机优惠的金额
				$arr_length = sizeof($fee_arr);
				$i = mt_rand(0, ($arr_length-1));
				$fee_money = $fee_arr[$i];
				$data = [
					'fee' => $fee_money,
					'order_sn' => $sn
				];
				try {
					$ret = OrderRandomFee::create($data);
					// Db::commit();
					$this->success('ok', $fee_money);
				} catch (Exception $e) {
					// Db::rollback();
					$this->error('提交失败，请尝试重新提交');
				}
			}
		}else{
			$this->error('订单已提交或已失效');
		}
	}

    /**获取错误信息.
     * 
     * @ApiInternal()
     */
    public function getError()
    {
        return $this->_error;
    }

    /**获取订单金额等信息
     * 
     * @ApiInternal()
     */
    private function getOrderInfo($sn)
    {
        if ($sn) {
            $field = 'id,sn,user_id,city_id,city_name,
					store_id,store_name,order_amount,
					platform,pay_type,pay_status,status,
					deliver_fee,packing_fee,original_amount,
					wallet_money_pay,wallet_given_fee';
            $row = LihuaOrder::where('sn', $sn)->field($field)->find();
            if ($row) {
                if ($row['status'] == 1) return $row;
                $this->setError($row['status'] > 1 ? '订单已支付或货到付款' : '订单已取消');
            } else $this->setError('订单不存在');
        } else $this->setError('订单不存在');
        return false;
	}

	private function getOrderInfo_refund($sn = '')
    {
		$order = LihuaOrder::getBySn($sn);
        if ($order) {
            return $order;
            $this->setError('订单不可退款');
        } else {
            $this->setError('订单不存在');
        }
        return false;
	}

	/**获取订单金额等信息
     * 
     * @ApiInternal()
     */
    private function updateOrderAct($sn)
    {
        //检查是否享受了某个促销活动
		$orderAct = LihuaOrderActivity::where(['order_sn'=>$sn])->count();
		if($orderAct>0){
			LihuaOrderActivity::where(['order_sn'=>$sn])->update(['paystatus' => 1]);
		}
		// Log::record('[ update LihuaOrderActivity ] INIT ' . $sn , 'info');
		/**
		 * 如果使用了现金抵用券，则需要更新现金抵用券的状态
		 * 1、查询出订单详情，判断是否使用过现金抵用券
		 * 2、更新现金券的状态
		 **/
		$orderi = LihuaOrder::where('sn', $sn)->find();
		// vouchers_fee > 0 则判断为使用了现金券
		if(floatval($orderi['vouchers_fee'])>0 && $orderi['vouchers_sn']!=''){
			LihuaVouchers::where(['sn'=>$orderi['vouchers_sn']])->update([
				'status' => 1,
				'user_id' => $orderi['user_id'],
				'use_time' => date('Y-m-d H:i:s'),
				'order_sn' => $sn,
				'update_time' => time(),
			]);
			$datas = [
				"city_id"		=> $orderi['city_id'],
				"user_id"		=> $orderi['user_id'],
				"day"			=> date('Y-m-d'),
				"voucher_sn"	=> $orderi['vouchers_sn'],
				"order_sn"		=> $sn,
				"use_type"		=> 2,
				"use_time"		=> date('Y-m-d H:i:s'),
				"create_time"	=> time(),
				"update_time"	=> time(),
			];
			$ret = LihuaVouchersLog::create($datas);
		}
	}
	
	/**获取钱包订单金额等信息
	 * 
	 * @ApiInternal()
	 */
	private function getWalletOrderInfo($sn)
	{
	    if ($sn) {
	        $row = LihuaWalletOrder::where('sn', $sn)->find();
	        if ($row) {
	            if ($row['status'] == 1) return $row;
	            $this->setError($row['status'] > 1 ? '订单已支付' : '订单已取消');
	        } else $this->setError('订单不存在');
	    } else $this->setError('订单不存在');
	    return false;
	}

    /**获取支付配置
     * 
     * @ApiInternal()
     */
    private function getPayConf($city_id = 0, $pay_type = 1, $platform = 'app')
    {
        if (in_array($pay_type, [1, 2])) {
            if (in_array($platform, ['app', 'xcx'])) {
                $table = $pay_type == 1 ? 'lihua_alipay' : 'lihua_wxpay';
                $type  = $platform == 'app' ? 1 : 2;
				// if($type==2) $city_id = 0;
                $row = Db::name($table)->where(['city_id' => $city_id, 'type' => 1])->field('id,city_id,type,name', true)->find();
                if ($row) {
					return $row;
				}else{
					$this->setError('未配置支付参数');
				}
            } else $this->setError('平台错误');
        } else $this->setError('请选择支付方式');
        return false;
	}

    /**获取订单信息及支付配置
     * 
     * @ApiInternal()
     */
    protected function getOrderInfoAndPayConf($sn = '', $pay_type = 1)
    {
        $info = $this->getOrderInfo($sn);
        if ($info === false) return false;

        $conf = $this->getPayConf($info['city_id'], $pay_type, $info['platform']);
        if ($conf === false) return false;
        return [$info, $conf];
	}

	protected function getOrderInfoAndPayConf_refund($sn = '', $pay_type = 1)
    {
        $info = $this->getOrderInfo_refund($sn);
        if ($info === false) return false;

        $conf = $this->getPayConf($info['city_id'], $pay_type, $info['platform']);
        if ($conf === false) return false;
        return [$info, $conf];
	}
	
	/**获取订单信息及支付配置
     * 
     * @ApiInternal()
     */
    protected function getWalletOrderInfoAndPayConf($sn = '', $pay_type = 1)
    {
        $info = $this->getWalletOrderInfo($sn);
        if ($info === false) return false;

        $conf = $this->getPayConf($info['city_id'], $pay_type, $info['platform']);
        if ($conf === false) return false;
        return [$info, $conf];
	}
	
	//获取某城市的钱包支付优惠活动
	//http://qianbao.lihua.com/api/wallet/getWalletAct
	public function getWalletAct(){
		$cityname = $this->request->request('cityname');
		//使用钱包余额支付订单
		$post_data = array(
			'cityname' => $cityname,
		);
		$ret = Http::post("http://qianbao.lihua.com/api/wallet/getWalletAct", $post_data);
		$res = json_decode($ret, true);
		$this->success($res);
	}

	//获取某城市的钱包支付优惠活动
	//http://qianbao.lihua.com/api/wallet/getWalletAct
	public function getWalletAct_test(){
		$cityname = $this->request->request('cityname');
		//使用钱包余额支付订单
		$post_data = array(
			'cityname' => $cityname,
		);
		$ret = Http::post("http://qianbao.lihua.com/api/wallet/getWalletAct_test", $post_data);
		$res = json_decode($ret, true);
		$this->success($res);
	}

    /**货到付款
     * 
     *
     * @ApiMethod  (POST)
     * @ApiParams  (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn  ({"code":1,"msg":"OK","time":"1550820650","data":{}})
     */
    public function code()
    {
        $sn = $this->request->post('sn');
		$field = 'id,sn,user_id,city_id,city_name,store_id,store_name,order_amount,platform,pay_type,pay_status,status,deliver_fee,packing_fee,original_amount';
        $info = LihuaOrder::where('sn', $sn)->field($field)->find();
        if (!$info) $this->error($this->getError());
		if($info['pay_status']==0){
			LihuaOrder::update(['pay_type' => 4, 'status' => 2], ['sn' => $sn]);
			$this->updateOrderAct($sn);
		}else{
			$this->error('订单已支付');
		}
        $this->success('OK');
    }
	
	/** 
	 * walletpay2 使用剩余金额抵扣部分订单金额
	 */
	public function walletpay2()
	{
	    $sn = $this->request->request('sn', '');
		$phone = $this->request->request('phone', 0);
		$cityname = $this->request->request('cityname', '');
		$pwd = $this->request->request('pwd');
		$uid = $this->request->request('uid');
		if (!$sn || !$phone || !$cityname || !$pwd || !$uid) $this->error('非法操作');
		$info = $this->getOrderInfo($sn);
		if ($info === false) $this->error($this->getError());
		//使用钱包余额支付订单
		$post_data = array(
			'phone' => $phone,
			'cityname' => $cityname,
			'order_id' => $sn,
			'price' => $order_amount,
			'user_id' => $uid,
			'paypwd' => $pwd,
			'apikey' => "Li4008800400Hua"
		);
		$ret = Http::post("http://qianbao.lihua.com/api/wallet/useBalancePayOrder", $post_data);
		$res = json_decode($ret, true);
		if($res['code']==0){
			$this->error($res['msg']);
		}else{
		    if($res['data']['result']==1){
		        // 钱包支付回调开始
                $row = $info;
                $use_giving = $res['data']['use_giving'];
                // $money = $row['order_amount'];
                $pay_time = date('Y-m-d H:i:s');
                $pay_ok = 1;
                $result_des = '钱包账号支付'.$order_amount.'元';
                $data = [
                    'type'           => 3, //钱包支付
                    'trade_no'       => $sn, //交易号
                    'out_trade_no'   => $sn, //订单号
                    'total_fee'      => $order_amount,
                    'order_id'       => $row['id'],
                    'user_id'        => $row['user_id'],//$res['attach']
                    'pay_ok'         => $pay_ok,
                    'pay_time'       => $pay_time,
                    'result_code'    => '',
                    'result_des'     => $result_des,
                    'callbackdata'   => "wallet pay ok",
                ];
				$paylog = LihuaPaylog::create($data);
                $data = [
                    'pay_type'   		=> 3,
                    'pay_status' 		=> 1,
                    'pay_time'   		=> $pay_time,
                    'status'     		=> 2,
                    'wallet_given_fee'	=> $use_giving
				];
				// //如果有随机优惠金额，则跟新订单优惠金额
				// if($has_fee){
				// 	if($has_fee['fee']>0){
				// 		$data['wallet_random_fee'] = $has_fee['fee'];
				// 	}
				// }
				// //如果免餐盒费
				// if($wallet_free_packing){
				// 	if($info['packing_fee']>0){
				// 		$data['wallet_packing_fee'] = $info['packing_fee'];
				// 	}
				// }
				// //如果使用了钱包赠送金额支付，那么实际支付金额需要减掉使用赠送金额支付的部分
				// if($use_giving>0){
				// 	$order_amount = bcsub($order_amount, $use_giving, 2);
				// }
				//如果免送餐费
				if($wallet_free_driver){
					$data['deliver_fee'] = 0;
					$data['original_amount'] = $info['original_amount'];
				}
				$data['order_amount'] = $order_amount;
                LihuaOrder::update($data, ['id' => $row['id']]);
				$this->updateOrderAct($sn);
				LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
                LihuaOrderPayment::create([
                    'city_id'    => $row['city_id'],
                    'order_id'   => $row['id'],
                    'order_sn'   => $row['sn'],
                    'user_id'    => $row['user_id'],
                    'pay_name'   => '丽华钱包',
                    'pay_money'  => $order_amount,
                    'is_voucher' => 0,
                ]);
                $this->success('ok');
            }else{
                $this->error($res['msg']);
            }
		}
	}

	/****
	 * wallet 
	 * 使用余额支付订单
	 * 这里需要计算
	 */
	public function walletpay()
	{
	    $sn = $this->request->request('sn', '');
		$phone = $this->request->request('phone', 0);
		$cityname = $this->request->request('cityname', '');
		$pwd = $this->request->request('pwd');
		$uid = $this->request->request('uid');
		$type = (int)$this->request->request('type', 0);
		
		if (!$sn || !$phone || !$cityname || !$pwd || !$uid) $this->error('非法操作');
		//此处需要redis控制方式重复扣款
		
		
		$info = $this->getOrderInfo($sn);
		if ($info === false) $this->error($this->getError());
		$order_amount = doubleval($info['order_amount']);

		$wallet_free_driver = false;
		$wallet_free_packing = false;
		$has_fee = false;
		if(!$type){
			//查询是否有随机优惠金额
			$has_fee = OrderRandomFee::where(['order_sn' => $sn])->find();
			if($has_fee){
				if ($has_fee['fee']>0){
					$order_amount = bcsub($order_amount, $has_fee['fee'], 2);
				}
			}
			//判断是否需要免运费
			//先判断当前订单是否需要送餐费
			if($info['deliver_fee']>0 || $info['packing_fee']>0){
				$post_data = array(
					'cityname' => $cityname,
				);
				$ret = Http::post("http://qianbao.lihua.com/api/wallet/getWalletAct", $post_data);
				$res = json_decode($ret, true);
				if($res['code']==1){
					//如果免送餐费
					if($res['data']['shipping_free']==1 && $info['deliver_fee']>0){ 
						$wallet_free_driver = true;
						$order_amount = bcsub($order_amount, $info['deliver_fee'], 2);
						$info['original_amount'] = bcsub($info['original_amount'], $info['deliver_fee'], 2);
					}
					//如果免餐盒费
					if($res['data']['packing_free']==1 && $info['packing_fee']>0){
						$wallet_free_packing = true;
						$order_amount = bcsub($order_amount, $info['packing_fee'], 2);
					}
				}
			}
		}
		

		//使用钱包余额支付订单
		$post_data = array(
			'phone' => $phone,
			'cityname' => $cityname,
			'order_id' => $sn,
			'price' => $order_amount,
			'user_id' => $uid,
			'paypwd' => $pwd,
			'apikey' => "Li4008800400Hua"
		);
		$ret = Http::post("http://qianbao.lihua.com/api/wallet/useBalancePayOrder", $post_data);
		$res = json_decode($ret, true);
		if($res['code']==0){
			$this->error($res['msg']);
		}else{
		    if($res['data']['result']==1){
				if(!!$res['data']['is_end']){
					// 钱包支付回调开始
					$row = $info;
					$use_giving = $res['data']['use_giving']; //赠送金额消费部分
					$use_money = $res['data']['use_money']; //本金消费部分
					// $money = $row['order_amount'];
					$pay_time = date('Y-m-d H:i:s');
					$pay_ok = 1;
					$result_des = '钱包账号支付'.$order_amount.'元';
					$data = [
						'type'           => 3, //钱包支付
						'trade_no'       => $sn, //交易号
						'out_trade_no'   => $sn, //订单号
						'total_fee'      => $order_amount,
						'order_id'       => $row['id'],
						'user_id'        => $row['user_id'],//$res['attach']
						'pay_ok'         => $pay_ok,
						'pay_time'       => $pay_time,
						'result_code'    => '',
						'result_des'     => $result_des,
						'callbackdata'   => "wallet pay ok",
					];
					$paylog = LihuaPaylog::create($data);
					$data = [
						'pay_type'   		=> 3,
						'pay_status' 		=> 1,
						'pay_time'   		=> $pay_time,
						'status'     		=> 2,
						'wallet_given_fee'	=> $use_giving,
						'wallet_money_pay'  => $use_money
					];
					//如果有随机优惠金额，则跟新订单优惠金额
					if($has_fee){
						if($has_fee['fee']>0){
							$data['wallet_random_fee'] = $has_fee['fee'];
						}
					}
					//如果免餐盒费
					if($wallet_free_packing){
						if($info['packing_fee']>0){
							$data['wallet_packing_fee'] = $info['packing_fee'];
						}
					}
					//如果使用了钱包赠送金额支付，那么实际支付金额需要减掉使用赠送金额支付的部分
					if($use_giving>0){
						$order_amount = bcsub($order_amount, $use_giving, 2);
					}
					//如果免送餐费
					if($wallet_free_driver){
						$data['deliver_fee'] = 0;
						$data['original_amount'] = $info['original_amount'];
					}
					$data['order_amount'] = $order_amount;
					LihuaOrder::update($data, ['id' => $row['id']]);
					$this->updateOrderAct($sn);
					LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
					LihuaOrderPayment::create([
						'city_id'    => $row['city_id'],
						'order_id'   => $row['id'],
						'order_sn'   => $row['sn'],
						'user_id'    => $row['user_id'],
						'pay_name'   => '丽华钱包',
						'pay_money'  => $order_amount,
						'is_voucher' => 0,
					]);
					$pay_money = $order_amount;
				}else{
					// 剩余金额需要继续支付
					/**
					 * 1、返回值，需要得到订单剩余金额
					 * 2、修改订单的wallet_money_pay字段，将钱包抵扣金额补充好
					 * 3、并且将 wallet_money_pay 字段返回给客户端
					 * **/
					// 钱包支付回调开始
					$row = $info;
					$use_giving = $res['data']['use_giving']; //use_money use_giving
					$use_money = $res['data']['use_money']; //use_money use_giving
					$pay_money = bcadd(floatval($use_giving), floatval($use_money), 2); //钱包支付的总金额

					// $money = $row['order_amount'];
					$pay_time = date('Y-m-d H:i:s');
					$pay_ok = 1;
					$result_des = '钱包账号支付'.$pay_money.'元';
					$data = [
						'type'           => 3, //钱包支付
						'trade_no'       => $sn, //交易号
						'out_trade_no'   => $sn, //订单号
						'total_fee'      => $pay_money,
						'order_id'       => $row['id'],
						'user_id'        => $row['user_id'],//$res['attach']
						'pay_ok'         => $pay_ok,
						'pay_time'       => $pay_time,
						'result_code'    => '',
						'result_des'     => $result_des,
						'callbackdata'   => "wallet pay ok",
					];
					$paylog = LihuaPaylog::create($data);
					$data = [
						'wallet_given_fee'	=> $use_giving, //钱包支付赠送金额部分
						'wallet_money_pay'	=> $use_money, //钱包支付本金部分
					];
					//如果使用了钱包赠送金额支付，那么实际支付金额需要减掉使用赠送金额支付的部分
					if($use_giving>0){
						$order_amount = bcsub($order_amount, $use_giving, 2);
					}
					$data['order_amount'] = $order_amount;
					LihuaOrder::update($data, ['id' => $row['id']]);

					// $this->updateOrderAct($sn);
					
					LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
					LihuaOrderPayment::create([
						'city_id'    => $row['city_id'],
						'order_id'   => $row['id'],
						'order_sn'   => $row['sn'],
						'user_id'    => $row['user_id'],
						'pay_name'   => '丽华钱包',
						'pay_money'  => $use_money,
						'is_voucher' => 0,
					]);
				}

				$balance = bcsub($info['order_amount'], $pay_money, 2);
				$this->success('ok', [
					'is_end' => $res['data']['is_end'],
					'pay_money' => $pay_money, //订单已经支付的金额
					'balance' => $balance, //订单余款
				]);
		        
            }else{
                $this->error($res['msg']);
            }
		}
	}
	
    /**北京地区VIP会员卡支付
     * 
     *
     * @ApiMethod  (POST)
     * @ApiParams  (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn  ({"code":1,"msg":"OK","time":"1550820650","data":{}})
     */
    public function vip()
    {
        $sn = $this->request->post('sn');
        $info = $this->getOrderInfo($sn);
        if ($info === false) $this->error($this->getError());
		$original_amount_s = $info['original_amount'];
		if(floatval($info['deliver_fee'])>0){
			$info['order_amount'] = bcsub($info['order_amount'], $info['deliver_fee'], 2);
			$original_amount_s = bcsub($info['original_amount'], $info['deliver_fee'], 2);
			$info['deliver_fee'] = 0;
		}
		if($info['pay_status']==0){
			LihuaOrder::where(['sn' => $sn])->update([
				'pay_type' => 5, 
				'status' => 2, 
				'deliver_fee' => $info['deliver_fee'], 
				'order_amount' => $info['order_amount'], 
				'original_amount' => $original_amount_s,
			]);
			$this->updateOrderAct($sn);
		}else{
			$this->error('订单已支付');
		}
        $this->success('OK');
	}
	
	/** 微信小程序——微信支付 已经切换到 n_pay_money
     * 
     *
     * @ApiMethod  (POST)
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn  ({"code":1,"msg":"OK","time":"1550820650","data":{"appid":"","partnerid":"","prepayid":"","package":"","noncestr":"","timestamp":"","sign":""}})
     */
    public function xcx_wxpay()
    {
        $sn  = $this->request->request('sn');
        $arr = $this->getOrderInfoAndPayConf($sn, 2);
        if ($arr === false) $this->error($this->getError());
        list($info, $conf) = $arr;
		$config = [
			'appid'      	=> $conf['xcx_id'],//微信开放平台上的应用ID
			'mch_id'     	=> $conf['mch_id'],//商户号
			'api_key'    	=> $conf['api_key'],//微信商户平台上自己设定的api密钥32位
			'notify_url' 	=> config('api_url') . '/pay/wxcb.html',//回调地址
			'trade_type' 	=> 'JSAPI',
		];
		$js_code = $this->request->request('js_code');
		$url = 'https://api.weixin.qq.com/sns/jscode2session';
		$params = [
			'appid'   		=> $conf['xcx_id'],
			'secret'  		=> $conf['app_secret'], //应用secret
			'js_code' 		=> $js_code,
			'grant_type' 	=> 'authorization_code',
		];
		$ret = Http::post($url, $params);
		$result = json_decode($ret, true);
		if(isset($result['openid'])){
			$config['openid'] = $result['openid'];
		}else{
			$this->error($result['msg']);
		}
		$wxpay = new WxPay($config);
		$cityname = '';
		if($info['city_name']=='常州'){ $cityname = 'cz'; };
		if($info['city_name']=='无锡'){ $cityname = 'wx'; };
		if($info['city_name']=='苏州'){ $cityname = 'sz'; };
		if($info['city_name']=='上海'){ $cityname = 'sh'; };
		if($info['city_name']=='南京'){ $cityname = 'nj'; };
		if($info['city_name']=='北京'){ $cityname = 'bj'; };
		if($info['city_name']=='广州'){ $cityname = 'gz'; };
		$body  = "lihua-{$cityname}-{$sn}";
		//计算需要支付的金额
		$n_pay_money = bcsub($info['order_amount'], $info['wallet_money_pay'], 2); //wallet_money_pay,wallet_given_fee
		$order = $wxpay->xcx_unifiedOrder($sn, $n_pay_money, $body);
		if ($order === false) $this->error($wxpay->err_msg);
		$this->success('OK', $order);
    }

    /**微信支付 已经切换到 n_pay_money
     * 
     * @ApiMethod  (POST)
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn  ({"code":1,"msg":"OK","time":"1550820650","data":{"appid":"","partnerid":"","prepayid":"","package":"","noncestr":"","timestamp":"","sign":""}})
     */
    public function wxpay()
    {
        $sn  = $this->request->request('sn');
        $arr = $this->getOrderInfoAndPayConf($sn, 2);
        if ($arr === false) $this->error($this->getError());
        list($info, $conf) = $arr;
		$openid = "";
		$config = [
			'appid'      	=> $conf['appid'],//微信开放平台上的应用ID
			'mch_id'     	=> $conf['mch_id'],//商户号
			'api_key'    	=> $conf['api_key'],//微信商户平台上自己设定的api密钥32位
			'notify_url' 	=> config('api_url') . '/pay/wxcb.html',//回调地址
			'trade_type' 	=> $info['platform'] == 'xcx' ? 'JSAPI' : 'APP',
		];
		if($info['platform']=='xcx'){
			$js_code = $this->request->request('js_code');
			$url = 'https://api.weixin.qq.com/sns/jscode2session';
			$params = [
				'appid'   		=> $conf['appid'],
				'secret'  		=> $conf['app_secret'], //应用secret
				'js_code' 		=> $js_code,
				'grant_type' 	=> 'authorization_code',
			];
			$ret = Http::post($url, $params);
			$result = json_decode($ret, true);
			if(!!$result['openid']){
				$config['openid'] = $result['openid'];
			}else{
				$this->error($result['msg']);
			}
		}
		$wxpay = new WxPay($config);
		$body  = "丽华快餐-{$info['city_name']}-{$info['store_name']}-订单{$sn}";

		$n_pay_money = bcsub($info['order_amount'], $info['wallet_money_pay'], 2); //wallet_money_pay,wallet_given_fee
		$order = $wxpay->unifiedOrder($sn, $n_pay_money, $body);
		// $order = $wxpay->unifiedOrder($sn, $info['order_amount'], $body);
		if ($order === false) $this->error($wxpay->err_msg);
		$this->success('OK', $order);
	}
	
	/*支付回调中调用钱包充值接口 */
	private function bc_userprepaid($data){
		//判断订单是否已经完成支付
		$info = $this->getWalletOrderInfo($data['wallet_sn']);
		if($info['status']==2){
			$this->success('返回成功');
		}else{
			$post_data = array(
				"cityname" => $data['cityname'],
				"price" => $data['price'],
				"phone" => $data['phone'],
				"getmoney" => $data['getmoney'],
				"user_id" => $data['user_id'],
				"activity_id" => $data['activity_id'],
				"wallet_sn" => $data['wallet_sn'],
			);
			Log::record('[ 钱包充值流程调试3 ' . $data['wallet_sn'] . ' ] INIT ' . $data['price'] . $data['cityname'] . $data['getmoney'] , 'info');
			$ret = Http::post("http://qianbao.lihua.com/api/wallet/userprepaid", $post_data);
			$res = json_decode($ret, true);
			if($res['code']==0){
				$this->error($res['msg']);
			}else{
				$this->success('返回成功', $res['data']);
			}
		}
	}
	
	/**钱包充值
	 * 
	 */
	public function userprepaid()
	{
		//获取传入参数
		$cityname = $this->request->request("cityname");
		$price = $this->request->request("price");
		$phone = $this->request->request("phone");
		$getmoney = $this->request->request("getmoney");
		$user_id = $this->request->request("user_id");
		$activity_id = $this->request->request("activity_id");
		$note = $this->request->request("wallet_sn");
		if (
			!$cityname || !$price || !$phone 
			|| !$getmoney || !$user_id || !$activity_id 
			|| !$note
		) $this->error('参数错误');
		$this->success('OK');

		//判断订单是否已经完成支付
		// $info = $this->getWalletOrderInfo($note);
		// if($info['status']==2){
		// 	$this->success('返回成功');
		// }else{
			// $post_data = array(
			// 	"cityname" => $cityname,
			// 	"price" => $price,
			// 	"phone" => $phone,
			// 	"getmoney" => $getmoney,
			// 	"user_id" => $user_id,
			// 	"activity_id" => $activity_id,
			// 	"wallet_sn" => $note
			// );
			// $ret = Http::post("http://qianbao.lihua.com/api/wallet/userprepaid", $post_data);
			// $res = json_decode($ret, true);
			// if($res['code']==0){
			// 	$this->error($res['msg']);
			// }else{
			// 	$this->success('返回成功', $res['data']);
			// }
		// }
	}
	
	/**支付回调，跟新钱包系统的充值账号
	 * 
	*/
	public function userprepaid_sys($cityname,$price,$phone,$getmoney,$user_id,$activity_id,$note)
	{
		$post_data = array(
		    "cityname" => $cityname,
			"price" => $price,
			"phone" => $phone,
			"getmoney" => $getmoney,
			"user_id" => $user_id,
			"activity_id" => $activity_id,
			"wallet_sn" => $note
		);
		$ret = Http::post("http://qianbao.lihua.com/api/wallet/userprepaid", $post_data);
		$res = json_decode($ret, true);
		if($res['code']==0){
			return false;
		}else{
			return true;
		}
	}
	
	/**钱包账号在线充值，微信支付
	 * 
	 *
	 * @ApiMethod  (POST)
	 * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
	 * @ApiParams  (name="sn", type="string", required=true, description="订单号")
	 * @ApiReturn  ({"code":1,"msg":"OK","time":"1550820650","data":{"appid":"","partnerid":"","prepayid":"","package":"","noncestr":"","timestamp":"","sign":""}})
	 */
	public function wallet_wxpay()
	{
		$city_id = $this->request->post('city_id');
		$pay_type = $this->request->post('pay_type');
		$platform  = $this->request->post('platform');
		$city_name  = $this->request->post('city_name');

		//判断用户是否已经绑定了手机号
		$user_id  = $this->auth->id;
		$users = User::where([ 'id' => $user_id ])->find();
		if(!$users['mobile']){
			$this->error("请先绑定手机号后在进行充值操作");
		}

		//北京地区需要却别对待
		if($city_id==1){
			$sn  = $this->request->post('sn');
			if($platform=='app'){
				$order = $this->getWalletOrderInfo($sn);
				$sss = json_encode($order);
				Log::record('[ 钱包充值流程调试1 ' . $sn . ' ] INIT ' . $sss , 'info');
				if($order){ 
					$conf = $this->getPayConf($city_id, $pay_type, $platform);
					if ($conf === false) $this->error($this->getError());
					$config = [
						'appid'      => $conf['appid'],//微信开放平台上的应用ID
						'mch_id'     => $conf['mch_id'],//商户号
						'api_key'    => $conf['api_key'],//微信商户平台上自己设定的api密钥32位
						'notify_url' => config('api_url') . '/pay/wallet_wxcb.html',//回调地址
						'trade_type' => 'APP',
					];
					$wxpay = new WxPay($config);
					$body  = "丽华快餐-{$city_name}钱包充值-订单{$sn}";
					$order = $wxpay->unifiedOrder($sn, $order['money'], $body);
					if ($order === false) $this->error($wxpay->err_msg);
					$this->success('OK', $order);
				}else{
					$this->error($this->getError());
				}
			}
			if($platform=='xcx'){
				$arr = $this->getWalletOrderInfoAndPayConf($sn, 2);
				if ($arr === false) $this->error($this->getError());
				list($info, $conf) = $arr;
				$config = [
					'appid'      	=> $conf['xcx_id'],//微信开放平台上的应用ID
					'mch_id'     	=> $conf['mch_id'],//商户号
					'api_key'    	=> $conf['api_key'],//微信商户平台上自己设定的api密钥32位
					'notify_url' 	=> config('api_url') . '/pay/wallet_wxcb.html',//回调地址
					'trade_type' 	=> 'JSAPI',
				];
				$js_code = $this->request->request('js_code');
				$url = 'https://api.weixin.qq.com/sns/jscode2session';
				$params = [
					'appid'   		=> $conf['xcx_id'],
					'secret'  		=> $conf['app_secret'], //应用secret
					'js_code' 		=> $js_code,
					'grant_type' 	=> 'authorization_code',
				];
				$ret = Http::post($url, $params);
				// return $this->success('OK', ['data'=> ]);
				$result = json_decode($ret, true);
				if(!!$result['openid']){
					$config['openid'] = $result['openid'];
				}else{
					$this->error($result['msg']);
				}
				$wxpay = new WxPay($config);
				$body  = "lihua-钱包充值-{$info['city_id']}-{$sn}";
				$order = $wxpay->xcx_unifiedOrder($sn, $info['money'], $body);
				if ($order === false) $this->error($wxpay->err_msg);
				$this->success('OK', $order);
			}
		}else{
			if($platform=='xcx'){
				$arr = $this->getWalletOrderInfoAndPayConf($sn, 2);
				if ($arr === false) $this->error($this->getError());
				list($info, $conf) = $arr;
				$config = [
					'appid'      	=> $conf['xcx_id'],//微信开放平台上的应用ID
					'mch_id'     	=> $conf['mch_id'],//商户号
					'api_key'    	=> $conf['api_key'],//微信商户平台上自己设定的api密钥32位
					'notify_url' 	=> config('api_url') . '/pay/wallet_wxcb.html',//回调地址
					'trade_type' 	=> 'JSAPI',
				];
				$js_code = $this->request->request('js_code');
				$url = 'https://api.weixin.qq.com/sns/jscode2session';
				$params = [
					'appid'   		=> $conf['xcx_id'],
					'secret'  		=> $conf['app_secret'], //应用secret
					'js_code' 		=> $js_code,
					'grant_type' 	=> 'authorization_code',
				];
				$ret = Http::post($url, $params);
				$result = json_decode($ret, true);
				$config['mid'] = $conf['mid'];
				$config['tid'] = $conf['tid'];
				$config['openid'] = isset($result['openid'])?$result['openid']:"";
				$wxpay 	= new WxPay($config);
				$url   	= "https://qr.chinaums.com/netpay-route-server/api/";
				$data  	= $wxpay->unionpay_unifiedOrder($sn, $info['money']);
				$params = json_encode($data);
				$ret 	= Http::post($url, $params);
				$res 	= json_decode($ret, true);
				$this->success('返回成功', $res);
			}else{
				$order = $this->getWalletOrderInfo($sn);
				$sss = json_encode($order);
				Log::record('[ 钱包充值流程调试1 ' . $sn . ' ] INIT ' . $sss , 'info');
				if($order){ 
					$conf = $this->getPayConf($city_id, $pay_type, $platform);
					if ($conf === false) $this->error($this->getError());
					$config = [
						'appid'      => $conf['appid'],//微信开放平台上的应用ID
						'mch_id'     => $conf['mch_id'],//商户号
						'api_key'    => $conf['api_key'],//微信商户平台上自己设定的api密钥32位
						'notify_url' => config('api_url') . '/pay/wallet_wxcb.html',//回调地址
						'trade_type' => 'APP',
					];
					$wxpay = new WxPay($config);
					$body  = "丽华快餐-{$city_name}钱包充值-订单{$sn}";
					$order = $wxpay->unifiedOrder($sn, $order['money'], $body);
					if ($order === false) $this->error($wxpay->err_msg);
					$this->success('OK', $order);
				}else{
					$this->error($this->getError());
				}
			}
		}
	}

    /**微信支付回调
     * 
     *
     * @ApiInternal()
     */
    public function wxcb()
    {
        $xml   = file_get_contents('php://input');
        $wxpay = new WxPay();
        $res   = $wxpay->xmlstr_to_array($xml);
        if ($res['return_code'] == 'SUCCESS') {
            if ($res['result_code'] == 'SUCCESS') {
                // $row = $this->getOrderInfo($res['out_trade_no']);
				$row = LihuaOrder::where(['sn'=> $res['out_trade_no']])->find();
                if ($row) {
					// $money = $res['total_fee'];
                    $money = round($res['total_fee']/100, 2);
                    $order_amount = $row['order_amount'];
                    //$checkMoney = (($money * 100) == $res['total_fee']);
					// Log::record('[ wxcb::->order_money res_total_fee  ] INIT ' . ($order_amount * 100) . ':::' .$res['total_fee'] . ':::::' . $checkMoney , 'info');
					if ($res['time_end']) {
						$time_end = date_create($res['time_end']);
						$pay_time = date_format($time_end,"Y-m-d H:i:s");
					}

					if ($res['result_code'] == 'SUCCESS') {
						$pay_ok = 1;
						$result_des = '交易支付成功';
					} else {
						$pay_ok = 0;
						$result_des = $res['err_code'].':'.$res['err_code_des'];
					}

					if (!isset($pay_time)) $pay_time = date('Y-m-d H:i:s');
					$data = [
						'type'           => 2,//微信支付
						'trade_no'       => $res['transaction_id'],
						'out_trade_no'   => $res['out_trade_no'],
						'total_fee'      => $money,
						'order_id'       => $row['id'],
						'user_id'        => $row['user_id'],//$res['attach']
						'pay_ok'         => $pay_ok,
						'pay_time'       => $pay_time,
						'result_code'    => $res['result_code'],
						'result_des'     => $result_des,
						'callbackdata'   => json_encode($res, JSON_UNESCAPED_UNICODE),
					];

					$paylog = LihuaPaylog::create($data);

					if ($res['result_code'] == 'SUCCESS' && $row['status'] == 1) {
						$data = [
							'pay_type'   => 2,
							'pay_status' => 1,
							'pay_time'   => $pay_time,
							'status'     => 2,
						];
						LihuaOrder::update($data, ['id' => $row['id']]);//跟新订单状态

						$this->updateOrderAct($row['sn']);

						LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
						LihuaOrderPayment::create([
							'city_id'    => $row['city_id'],
							'order_id'   => $row['id'],
							'order_sn'   => $row['sn'],
							'user_id'    => $row['user_id'],
							'pay_name'   => '微支付',
							'pay_money'  => $money,
							'is_voucher' => 0,
						]);
					}
                }
            }
        }
        return xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
    }
	
	/** 钱包充值，微信支付回调
	 * 
	 *
	 * @ApiInternal()
	 */
	public function wallet_wxcb()
	{
	    $xml   = file_get_contents('php://input');
	    $wxpay = new WxPay();
	    $res   = $wxpay->xmlstr_to_array($xml);
	    if ($res['return_code'] == 'SUCCESS') {
	        if ($res['result_code'] == 'SUCCESS') {
	            $row = $this->getWalletOrderInfo($res['out_trade_no']);
	            if ($row) {
	                $money = $row['money'];
	                // if ($money * 100 == $res['total_fee']) {
						if ($res['time_end']) {
                            $time_end = date_create($res['time_end']);
                            $pay_time = date_format($time_end,"Y-m-d H:i:s");
                        }
	                    if ($res['result_code'] == 'SUCCESS') {
	                        $pay_ok = 1;
	                        $result_des = '交易支付成功';
	                    } else {
	                        $pay_ok = 0;
	                        $result_des = $res['err_code'].'：'.$res['err_code_des'];
	                    }
	                    if (!isset($pay_time)) $pay_time = date('Y-m-d H:i:s');
	                    $data = [
	                        'type'           => 2,//微信支付
	                        'trade_no'       => $res['transaction_id'],
	                        'out_trade_no'   => $res['out_trade_no'],
	                        'total_fee'      => $money,
	                        'order_id'       => $row['id'],
	                        'user_id'        => $row['user_id'],//$res['attach']
	                        'pay_ok'         => $pay_ok,
	                        'pay_time'       => $pay_time,
	                        'result_code'    => $res['result_code'],
	                        'result_des'     => $result_des,
	                        'callbackdata'   => json_encode($res, JSON_UNESCAPED_UNICODE),
	                    ];
	                    $paylog = LihuaPaylog::create($data);
						if ($res['result_code'] == 'SUCCESS' && $row['status'] == 1) {
	                        $data = [
	                            'pay_type'   => 2,
	                            'pay_time'   => $pay_time,
	                            'status'     => 2,
	                        ];
	                        LihuaWalletOrder::update($data, ['id' => $row['id']]);
	                        LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
	                        LihuaOrderPayment::create([
	                            'city_id'    => $row['city_id'],
	                            'order_id'   => $row['id'],
	                            'order_sn'   => $row['sn'],
	                            'user_id'    => $row['user_id'],
	                            'pay_name'   => '微支付',
	                            'pay_money'  => $money,
	                            'is_voucher' => 0,
	                        ]);
							$city_info  = LihuaCity::getCityInfo($row['city_id']);
							Log::record('[ 钱包充值流程调试2 ' . $city_info['city_name'] . ' ] INIT ' . $row['money'] . $row['mobile'] . $row['getmoney'] , 'info');
							//支付回调，写入钱包充值系统中
							$this->bc_userprepaid(
								[
									"cityname" => $city_info['city_name'],
									"price" => $row['money'],
									"phone" => $row['mobile'],
									"getmoney" => $row['getmoney'],
									"user_id" => $row['user_id'],
									"activity_id" => $row['actid'],
									"wallet_sn" => $row['sn']
								]
							);
							$this->userprepaid_sys(
								$city_info['city_name'],
								$row['money'],
								$row['mobile'],
								$row['getmoney'],
								$row['user_id'],
								$row['actid'],
								$row['sn']
							);
	                    }
	                // }
	            }
	        }
	    }
	    return xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
	}

	/** 钱包充值，银联微信支付回调
	 * 
	 * @ApiInternal()
	 */
	public function wallet_wx_yl_cb(){
	    $xml   = file_get_contents('php://input');
	    $wxpay = new WxPay();
	    $res   = $wxpay->xmlstr_to_array_unionpay($xml);
	    if ($res['status'] == 'TRADE_SUCCESS') {
			$merOrderId = explode("_", $res['merOrderId']);
			// Log::record('[ unionpay_wxcb ] INIT ' . $merOrderId[1] . "_" . $res['merOrderId'], 'info');
			$row = $this->getWalletOrderInfo($merOrderId[1]);
			if ($row) {
				$money = round($res['totalAmount']/100, 2);
				// if ($money * 100 == $res['total_fee']) {
					$pay_time = date_format("Y-m-d H:i:s");
					if ($res['status'] == 'TRADE_SUCCESS') {
						$pay_ok = 1;
						$result_des = '交易支付成功';
					} else {
						$pay_ok = 0;
						$dis = [
							"NEW_ORDER" => "新订单",
							"UNKNOWN" => "不明确的交易状态",
							"TRADE_CLOSED" => "支付失败",
							"WAIT_BUYER_PAY" => "等待买家付款",
							"TRADE_SUCCESS" => "支付成功",
							"TRADE_REFUND" => "订单转入退货流程",
						];
						$result_des = $res['status'].'：'.$dis[$res['status']];
					}
					if (!isset($pay_time)) $pay_time = date('Y-m-d H:i:s');
					$data = [
						'type'           => 6,//微信支付
						'trade_no'       => $merOrderId,
						'out_trade_no'   => $merOrderId[1],
						'total_fee'      => $money,
						'order_id'       => $row['id'],
						'user_id'        => $row['user_id'],//$res['attach']
						'pay_ok'         => $pay_ok,
						'pay_time'       => $pay_time,
						'result_code'    => $res['status'],
						'result_des'     => $result_des,
						'callbackdata'   => json_encode($res, JSON_UNESCAPED_UNICODE),
					];
					$paylog = LihuaPaylog::create($data);
					if ($res['status'] == 'TRADE_SUCCESS' && $row['status'] == 1) {
						$data = [
							'pay_type'   => 6,
							'pay_time'   => $pay_time,
							'status'     => 2,
						];
						LihuaWalletOrder::update($data, ['id' => $row['id']]);
						LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
						LihuaOrderPayment::create([
							'city_id'    => $row['city_id'],
							'order_id'   => $row['id'],
							'order_sn'   => $row['sn'],
							'user_id'    => $row['user_id'],
							'pay_name'   => '微支付YL',
							'pay_money'  => $money,
							'is_voucher' => 0,
						]);
						$city_info  = LihuaCity::getCityInfo($row['city_id']);
						Log::record('[ 钱包充值流程调试2 ' . $city_info['city_name'] . ' ] INIT ' . $row['money'] . $row['mobile'] . $row['getmoney'] , 'info');
						//支付回调，写入钱包充值系统中
						$this->bc_userprepaid(
							[
								"cityname" => $city_info['city_name'],
								"price" => $row['money'],
								"phone" => $row['mobile'],
								"getmoney" => $row['getmoney'],
								"user_id" => $row['user_id'],
								"activity_id" => $row['actid'],
								"wallet_sn" => $row['sn']
							]
						);
						$this->userprepaid_sys(
							$city_info['city_name'],
							$row['money'],
							$row['mobile'],
							$row['getmoney'],
							$row['user_id'],
							$row['actid'],
							$row['sn']
						);
					}
				// }
			}
	    }
	    return xml(['return_code' => 'SUCCESS', 'return_msg' => 'OK']);
	}

    /** 阿里支付 已经切换到 n_pay_money
	 * 
     * @ApiMethod  (POST)
     * @ApiHeaders (name=token, type=string, required=true, description="请求的Token")
     * @ApiParams  (name="sn", type="string", required=true, description="订单号")
     * @ApiReturn  ({"code":1,"msg":"OK","time":"1550820650","data":{"result":""}})
     */
    public function alipay()
    {
        $sn  = $this->request->post('sn');
        $arr = $this->getOrderInfoAndPayConf($sn, 1);
        if ($arr === false) $this->error($this->getError());
        list($info, $conf) = $arr;

        $config  = [
            'gatewayUrl'         => 'https://openapi.alipay.com/gateway.do',
            'appId'              => $conf['appid'],//应用ID
            'signType'           => 'RSA2',
            'notifyUrl'          => config('api_url') . '/pay/alicb.html',//回调地址
            'rsaPrivateKey'      => $conf['private_key'],//应用私钥
            'alipayrsaPublicKey' => $conf['public_key'],//支付宝公钥
        ];

        $alipay  = new AliPay($config);
        $subject = "丽华快餐-{$info['city_name']}-{$info['store_name']}-订单{$sn}";

		$n_pay_money = bcsub($info['order_amount'], $info['wallet_money_pay'], 2); //wallet_money_pay,wallet_given_fee
		//$order = $wxpay->unifiedOrder($sn, $n_pay_money, $body);

        $data    = $alipay->unifiedOrder($sn, $n_pay_money, $subject, $info['platform']);
        if ($data !== false) $this->success('OK', $data);
        $this->error($alipay->err_msg);
    }

	public function wallet_alipay(){
		$city_id = $this->request->post('city_id');
		$pay_type = $this->request->post('pay_type');
		$platform  = $this->request->post('platform');
		$city_name  = $this->request->post('city_name');
		$sn  = $this->request->post('sn');
		$info = $this->getWalletOrderInfo($sn);
		if($info){
			$conf = $this->getPayConf($city_id, $pay_type, $platform);
			if ($conf === false) $this->error($this->getError());
			$config  = [
			    'gatewayUrl'         => 'https://openapi.alipay.com/gateway.do',
			    'appId'              => $conf['appid'],//应用ID
			    'signType'           => 'RSA2',
			    'notifyUrl'          => config('api_url') . '/pay/wallet_alicb.html',//回调地址
			    'rsaPrivateKey'      => $conf['private_key'],//应用私钥
			    'alipayrsaPublicKey' => $conf['public_key'],//支付宝公钥
			];
			
			$alipay  = new AliPay($config);
			$subject = "丽华快餐-{$city_name}钱包充值-订单{$sn}";
			$data    = $alipay->unifiedOrder($sn, $info['money'], $subject, $info['platform']);
			if ($data !== false) $this->success('OK', $data);
			$this->error($alipay->err_msg);
		}else{
			$this->error($this->getError());
		}
	}
	
	/**阿里支付回调
	 * 
	 *
	 * @ApiInternal()
	 */
	public function wallet_alicb()
	{
	    require_once ROOT_PATH . '/extend/my/alipay/AopClient.php';
	    $sn  = $_POST['out_trade_no'];
		$info = $this->getWalletOrderInfo($sn);
	    if ($info === false) $this->error($this->getError());
		$conf = $this->getPayConf($info['city_id'], 1, $info['platform']);
		if ($conf === false) $this->error($this->getError());
		Log::record('[wallet_alicbjwhklk::->order_money res_total_fee]INIT', 'info');
	    $aop  = new \AopClient;
	    $aop->alipayrsaPublicKey = $conf['public_key'];
	    $flag = $aop->rsaCheckV1($_POST, null, "RSA2");
	    if ($flag) {
	
	        $row = $info;
	        if ($row) {
	            $money = $row['money'];
	            if ($money == $_POST['total_amount']) {
	
	                $status = [
	                    'WAIT_BUYER_PAY' =>'等待买家付款',
	                    'TRADE_CLOSED'   =>'未付款超时关闭',
	                    'TRADE_SUCCESS'  =>'交易支付成功',
	                    'TRADE_FINISHED' =>'交易结束',
	                ];

					$pay_time = date('Y-m-d H:i:s');
					if(isset($_POST['gmt_payment'])){
						$pay_time = $_POST['gmt_payment'];
					}
	
	                $data = [
	                    'type'           => 1,//支付宝支付
	                    'trade_no'       => $_POST['trade_no'],
	                    'out_trade_no'   => $_POST['out_trade_no'],
	                    'total_fee'      => $_POST['total_amount'],
	                    'order_id'       => $row['id'],
	                    'user_id'        => $row['user_id'],
	                    'pay_ok'         => in_array($_POST['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED']) ? 1 : 0,
	                    'pay_time'       => $pay_time,
	                    'result_code'    => $_POST['trade_status'],
	                    'result_des'     => isset($status[$_POST['trade_status']]) ? $status[$_POST['trade_status']] : $_POST['trade_status'],
	                    'callbackdata'   => json_encode($_POST, JSON_UNESCAPED_UNICODE),
	                ];
	
	                $paylog = LihuaPaylog::create($data);
	
	                if (in_array($_POST['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED']) && $row['status'] == 1) {
	                    $data = [
	                        'pay_type'   => 1,
	                        'pay_time'   => $pay_time,
	                        'status'     => 2,
	                    ];
						LihuaWalletOrder::update($data, ['id' => $row['id']]);
						$city_info  = LihuaCity::getCityInfo($row['city_id']);
						//此处需要跟新钱包系统中的余额
						$this->userprepaid_sys(
							$city_info['city_name'],
							$row['money'],
							$row['mobile'],
							$row['getmoney'],
							$row['user_id'],
							$row['actid'],
							$row['sn']
						);
						
						LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
						
						//支付回调，写入钱包充值系统中
						$this->bc_userprepaid(
							[
								"cityname" => $city_info['city_name'],
								"price" => $row['money'],
								"phone" => $row['mobile'],
								"getmoney" => $row['getmoney'],
								"user_id" => $row['user_id'],
								"activity_id" => $row['actid'],
								"wallet_sn" => $row['sn']
							]
						);

	                    LihuaOrderPayment::create([
	                        'city_id'    => $row['city_id'],
	                        'order_id'   => $row['id'],
	                        'order_sn'   => $row['sn'],
	                        'user_id'    => $row['user_id'],
	                        'pay_name'   => '支付宝',
	                        'pay_money'  => $money,
	                        'is_voucher' => 0,
	                    ]);
	                }
	
	            }
	        }
	        exit('success');
	    }
	    exit('error');
	}
	
    /**阿里支付回调
     * 
     *
     * @ApiInternal()
     */
    public function alicb()
    {
        require_once ROOT_PATH . '/extend/my/alipay/AopClient.php';

        $sn  = $_POST['out_trade_no'];
        $arr = $this->getOrderInfoAndPayConf($sn, 1);
        if ($arr === false) exit('error');
        list($info, $conf) = $arr;

        $aop  = new \AopClient;
        $aop->alipayrsaPublicKey = $conf['public_key'];
        $flag = $aop->rsaCheckV1($_POST, null, "RSA2");
        if ($flag) {

            $row = LihuaOrder::where('sn', $sn)
                ->field('id,sn,user_id,city_id,store_id,order_amount,status')->find();
            if ($row) {
                $money = $_POST['total_amount'];
                $order_amount = $row['order_amount'];
                // if ($money == $_POST['total_amount']) {
                    // $checkMoney = ($money == $_POST['total_amount']);
					// Log::record('[ alicb::->order_money total_amount  ] INIT ' . $order_amount . ':::' . $_POST['total_amount'] . ':::::' . $checkMoney , 'info');

                    $status = [
                        'WAIT_BUYER_PAY' =>'等待买家付款',
                        'TRADE_CLOSED'   =>'未付款超时关闭',
                        'TRADE_SUCCESS'  =>'交易支付成功',
                        'TRADE_FINISHED' =>'交易结束',
                    ];

					$pay_time = date('Y-m-d H:i:s');
					if(isset($_POST['gmt_payment'])){
						$pay_time = $_POST['gmt_payment'];
					}

                    $data = [
                        'type'           => 1,//支付宝支付
                        'trade_no'       => $_POST['trade_no'],
                        'out_trade_no'   => $_POST['out_trade_no'],
                        'total_fee'      => $_POST['total_amount'],
                        'order_id'       => $row['id'],
                        'user_id'        => $row['user_id'],
                        'pay_ok'         => in_array($_POST['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED']) ? 1 : 0,
                        'pay_time'       => $pay_time,
                        'result_code'    => $_POST['trade_status'],
                        'result_des'     => isset($status[$_POST['trade_status']]) ? $status[$_POST['trade_status']] : $_POST['trade_status'],
                        'callbackdata'   => json_encode($_POST, JSON_UNESCAPED_UNICODE),
                    ];

                    $paylog = LihuaPaylog::create($data);

                    if (in_array($_POST['trade_status'], ['TRADE_SUCCESS', 'TRADE_FINISHED']) && $row['status'] == 1) {
                        $data = [
                            'pay_type'   => 1,
                            'pay_status' => 1,
                            'pay_time'   => $pay_time,
                            'status'     => 2,
                        ];
						LihuaOrder::update($data, ['id' => $row['id']]);
						
						//检查是否享受了某个促销活动
						$this->updateOrderAct($row['sn']);
						
                        LihuaPaylog::update(['upstatus' => 1], ['id' => $paylog->id]);
                        LihuaOrderPayment::create([
                            'city_id'    => $row['city_id'],
                            'order_id'   => $row['id'],
                            'order_sn'   => $row['sn'],
                            'user_id'    => $row['user_id'],
                            'pay_name'   => '支付宝',
                            'pay_money'  => $money,
                            'is_voucher' => 0,
                        ]);
                    }

                // }
            }
            exit('success');
        }
        exit('error');
    }
}
